package com.erpanderp.wam.ac.view.reimbursement;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.swing.SwingWorker;

import org.primefaces.context.RequestContext;

import com.erpanderp.wam.ac.model.entity.project.ProjectAssignment;
import com.erpanderp.wam.ac.model.entity.project.ProjectAssignmentDetail;
import com.erpanderp.wam.ac.model.entity.reimbursement.ProjectPerdiem;
import com.erpanderp.wam.ac.model.entity.reimbursement.ProjectPerdiemDetail;
import com.erpanderp.wam.ac.model.service.project.ProjectAssignmentDAO;
import com.erpanderp.wam.ac.model.service.reimbursement.ProjectPerdiemDAO;
import com.erpanderp.wam.ac.model.service.reimbursement.ProjectPerdiemDetailDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMHostManager;


@ViewScoped
@ManagedBean
public class ApproveProjectPerdiemsBean {
	HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
	ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	private String projectPerdiemCode;
	private String employeeCode;
	private String projectAssignmentCode;
	private ProjectPerdiem projectPerdiem = new ProjectPerdiem();
	private ProjectPerdiemDetail projectPerdiemDetail = new ProjectPerdiemDetail();
	private ProjectPerdiemDAO projectPerdiemDAO = new ProjectPerdiemDAO();
	private ProjectAssignment projectAssignment = new ProjectAssignment();
	private ProjectAssignmentDAO projectAssignmentDAO = new ProjectAssignmentDAO();
	private ProjectAssignmentDetail projectAssignmentDetail = new ProjectAssignmentDetail();
	private EmailUtil emailUtil = new EmailUtil();
	private String EMAIL_MESSAGE;
	private boolean FORM_VALID;
	private boolean renderDailog;
	private String revision;
	private String revisionCount;
	private ProjectPerdiemDetailDAO projectPerdiemDetailDAO = new ProjectPerdiemDetailDAO();
	private List<ProjectPerdiem> projectPerdiemsList = new ArrayList<ProjectPerdiem>();
	private String revisionParameter;
	private boolean recommendeRenderer;
	private boolean recommendeDialogRenderer;
	private boolean checkForUpdatesRenderer;
	private List<ProjectPerdiemDetail> projectPerdiemDetailsList = new ArrayList<ProjectPerdiemDetail>();
	
	public ApproveProjectPerdiemsBean(){
		
		projectPerdiemDAO = new ProjectPerdiemDAO();
		projectPerdiemCode = request.getParameter("projectPerdiemCode");
		revisionParameter = request.getParameter("revision");
		System.out.println("PROJECT PERDIEM CODE "+projectPerdiemCode);
		employeeCode = request.getParameter("employeeCode");
		projectAssignmentCode = request.getParameter("projectAssignmentCode");
		if(!(projectPerdiemCode.equals("") && !(employeeCode.equals("")) && !(projectAssignmentCode.equals("")))){
		 projectPerdiem = projectPerdiemDAO.getProjectPerdiemByProjectPerdiemCode(projectPerdiemCode);
		 //projectPerdiemDetail = projectPerdiemDAO.getProjectPerdiemDetailsByProjectPerdiemId(projectPerdiem.getProjectPerdiemId());
		 projectPerdiemDetail = projectPerdiemDetailDAO.getProjectPerdiemDetailsByProjectPerdiemIdAndRevision(projectPerdiem.getProjectPerdiemId(), revisionParameter);
		 projectAssignment = projectAssignmentDAO.getProjectAssignmentByProjectAssignmentIdAndEmployeeId(projectAssignmentCode, projectPerdiem.getEmployee().getEmployeeId());
		 projectAssignmentDetail = projectAssignmentDAO.getProjectAssignmentDetailByProjectAssignmentId(projectAssignment.getProjectAssignmentId());
		}else{
			ValidationUtil.gotoLoginPage();
		}
		
	 	
	}
		public void recommendProjectPerdiems(){
			
		    
			projectPerdiemDetailsList = projectPerdiemDetailDAO.getProjectPerdiemsDetailsByProjectPerdiemId(projectPerdiem.getProjectPerdiemId());
			System.out.println("PROJECT PERDIEMS LIST SIZE "+projectPerdiemDetailsList.size());
			if(projectPerdiemDetailsList.size() > 0){
				for(ProjectPerdiemDetail projectPerdiemDetail : projectPerdiemDetailsList){
					revisionCount = projectPerdiemDAO.getRevisionCountByPerdiemId(projectPerdiemDetail.getProjectPerdiem().getProjectPerdiemId());
					revision = "R"+revisionCount;					
				   
				}
				System.out.println("REVISION COUNT = "+revisionCount);
			}
			
			 System.out.println("-------------PARAMETER REVISION IS ------------"+revisionParameter);
			 ProjectPerdiemDetail projectPerdiemDetail = new ProjectPerdiemDetailDAO().getProjectPerdiemDetailsByProjectPerdiemIdAndRevision(projectPerdiem.getProjectPerdiemId(), revisionParameter);

			if(projectPerdiemDetail.getRevision().equals(revisionParameter)){
				
				validateRecommendForm();
				if(FORM_VALID){
				projectPerdiemDetail.setRecommendationStatus(CommonLookup.PERDIEM_RECOMMENDED__STATUS);
				
				if(projectPerdiemDAO.updateProjectPerdiemsDetails(projectPerdiemDetail)){
					 FacesMessage msg = new FacesMessage("Project Perdiems Request form recommended Successful", null);  
				     FacesContext.getCurrentInstance().addMessage(null, msg);
					}else{
						 FacesMessage msg = new FacesMessage("Project Perdiems Request form recommendation failled", null);  
					     FacesContext.getCurrentInstance().addMessage(null, msg);
					}
					
					Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
					String domainName = context.getInitParameter("domainName");
					String messageString ="";		

				    /*
				     * MAIL TO APPROVER EMAIL
				     */
					emailUtil = new EmailUtil();
					if(hostsMap.get(CommonLookup.DEV_EMAIL) == null){
						String[] to = {CommonLookup.PROJECTASSIGNMENT_DOMESTIC_INTERNATIONAL_APPROVER_EMAIL};
						emailUtil.setRecieverAddresses(to);
					}else{
						String[] to = {hostsMap.get(CommonLookup.DEV_EMAIL)};
						emailUtil.setRecieverAddresses(to);
					}
							
					String requestURL = "ac/reimbursement/approvevpprojectperdiems.html?projectPerdiemCode=" +projectPerdiemCode+"&projectAssignmentCode="+projectAssignment.getProjectAssignmentCode()+"&employeeCode="+projectPerdiem.getEmployee().getEmployeeCode()+"&revision="+projectPerdiemDetail.getRevision() ;
					String privateLink = "http://" + hostsMap.get(CommonLookup.PRIVATEHOST) + "/" + domainName + "/" + requestURL;
					String publicLink = "http://" + hostsMap.get(CommonLookup.PUBLICHOST) + "/"	+ domainName + "/" + requestURL;
					
					messageString = "Dear VP"  +
											",<br /><br />" +
											
											"<table style='border: 1px solid #d9d9d9;'>" +
									        "<tr> <td>Employee Name</td><td> : </td><td>" + projectPerdiem.getEmployee().getFirstName()+" "+projectPerdiem.getEmployee().getLastName()+"</td></tr>" +
									        "<tr> <td>Employee Id</td><td> : </td><td>" + projectPerdiem.getEmployee().getEmployeeCode()+ " </td></tr>" +
									        "<tr> <td>Travel Request Id</td><td> : </td><td>" + projectPerdiem.getProjectPerdiemCode()+ " </td></tr>" +
									       			       
									        "</table><br/>"+							       
									        "<a style='color:#FF9933;font-weight: bold;' href=\""+
									        privateLink + "\">" + "Please click here to Approve/Reject project perdiem form request" + "</a /><br />"+
											"(Employees who are in Hyderabad office)"+"<br /><br />"+
											"<a style='color:#FF9933;font-weight: bold;' href=\""+
											publicLink + "\">" + "Please click here to Approve/Reject project perdiem form request" + "</a /><br />"+
											"(out side Hyderabad office)"+"<br /><br />"+
											
											"Thanks & Regards, <br />"+CommonLookup.WAM_DEVTEAM_SIGNATURE;
					emailUtil.setMessage(messageString);
					emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
					
					emailUtil.setSubject("WAM -"+projectPerdiem.getEmployee().getFirstName()+" "+projectPerdiem.getEmployee().getLastName() +"( "+projectPerdiemCode+" ) - Project Perdiems Request");
					
					SwingWorker worker = new SwingWorker<String, Object>() {
						@Override
						protected String doInBackground() throws Exception {
							EMAIL_MESSAGE = emailUtil.processAndSendEmail();
							return null;
						}

						@Override
						protected void done() {
								System.out.println("DONE " + EMAIL_MESSAGE);		
						}
					};
					worker.execute();
					System.out.println( "BEFORE RETURNING: " + EMAIL_MESSAGE);
				
					
				}else{
					System.out.println("FORM NOT VALID");
				}

			}else{
				//RequestContext.getCurrentInstance().execute("updateForm.show();");
				checkForUpdatesRenderer = true;
				renderDailog = true;
				System.out.println("REFRESH THE PAGE");
                System.out.println("USER UPDATED THE DETAILS");
				
				
			}
			
		}
		
		public void rejectRecommendProjectPerdiems(){
			validateRecommendForm();
			if(FORM_VALID){
			projectPerdiemDetail.setRecommendationStatus(CommonLookup.PERDIEM_REJECT__STATUS);
			
			if(projectPerdiemDAO.updateProjectPerdiemsDetails(projectPerdiemDetail)){
				 FacesMessage msg = new FacesMessage("Project Perdiems Request form rejected", null);  
			     FacesContext.getCurrentInstance().addMessage(null, msg);
				}else{
					 FacesMessage msg = new FacesMessage("Project Perdiems Request form rejection failled", null);  
				     FacesContext.getCurrentInstance().addMessage(null, msg);
				}
				
				Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
				String domainName = context.getInitParameter("domainName");
				String messageString ="";		

			    /*
			     * MAIL TO APPLIED EMPLOYEE EMAIL
			     */
				emailUtil = new EmailUtil();
				if(hostsMap.get(CommonLookup.DEV_EMAIL) == null){
					String[] to = {projectPerdiem.getEmployee().getEmail()};
					emailUtil.setRecieverAddresses(to);
				}else{
					String[] to = {hostsMap.get(CommonLookup.DEV_EMAIL)};
					emailUtil.setRecieverAddresses(to);
				}
						
				/*String requestURL = "ac/reimbursement/approveprojectperdiems.html?projectPerdiemCode=" +projectPerdiemCode+"&projectAssignmentCode="+projectAssignment.getProjectAssignmentCode()+"&employeeCode="+projectPerdiem.getEmployee().getEmployeeCode() ;
				String privateLink = "http://" + hostsMap.get(CommonLookup.PRIVATEHOST) + "/" + domainName + "/" + requestURL;
				String publicLink = "http://" + hostsMap.get(CommonLookup.PUBLICHOST) + "/"	+ domainName + "/" + requestURL;
				*/
				messageString = "Dear Employee"  +
										",<br /><br />" +
										
										"<table style='border: 1px solid #d9d9d9;'>" +
								        "<tr> <td>Employee Name</td><td> : </td><td>" + projectPerdiem.getEmployee().getFirstName()+" "+projectPerdiem.getEmployee().getLastName()+"</td></tr>" +
								        "<tr> <td>Employee Id</td><td> : </td><td>" + projectPerdiem.getEmployee().getEmployeeCode()+ " </td></tr>" +
								        "<tr> <td>Project Perdiem Request Id</td><td> : </td><td>" + projectPerdiem.getProjectPerdiemCode()+ " </td></tr>" +
								       			       
								        "</table><br/>"+							       
								        
										
										"Thanks & Regards, <br />"+CommonLookup.WAM_DEVTEAM_SIGNATURE;
				emailUtil.setMessage(messageString);
				emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
				emailUtil.setSubject("WAM -"+projectPerdiem.getEmployee().getFirstName()+" "+projectPerdiem.getEmployee().getLastName() +"( "+projectPerdiemCode+" ) - Project Perdiems Request");
				
				SwingWorker worker = new SwingWorker<String, Object>() {
					@Override
					protected String doInBackground() throws Exception {
						//EMAIL_MESSAGE = emailUtil.processAndSendEmail();
						return null;
					}

					@Override
					protected void done() {
							System.out.println("DONE " + EMAIL_MESSAGE);		
					}
				};
				worker.execute();
				System.out.println( "BEFORE RETURNING: " + EMAIL_MESSAGE);
			
				
			}else{
				System.out.println("FORM NOT VALID");
			}
		}
		
		public void updateForm(){
			System.out.println("EMAIL NOTIFICATION FOR UPDATES");
		    //revisionParameter = revision;
			//projectPerdiemDetail = projectPerdiemDetailDAO.getProjectPerdiemDetailsByProjectPerdiemIdAndRevision(projectPerdiem.getProjectPerdiemId(), revisionParameter);
			RequestContext.getCurrentInstance().execute("updateForm.hide();");
			//recommendeRenderer = true;
			checkForUpdatesRenderer = false;
			
		}
		public void cancelUpdate(){
			System.out.println("CANCELLING UPDATE");
			RequestContext.getCurrentInstance().execute("updateForm.hide();");
			checkForUpdatesRenderer = false;
		}
		
		
		public void validateRecommendForm(){
			 System.out.println("IN VALIDATE METHOD");
				FORM_VALID = true;
				if(ValidationUtil.isEmpty(projectPerdiemDetail.getRecommendationComment(), "Recommendation comments", null, FacesContext.getCurrentInstance()) != null){
					FORM_VALID = false;
				}
				
				
						
				
		 }
	

	public String getProjectPerdiemCode() {
		return projectPerdiemCode;
	}



	public void setProjectPerdiemCode(String projectPerdiemCode) {
		this.projectPerdiemCode = projectPerdiemCode;
	}



	public String getEmployeeCode() {
		return employeeCode;
	}



	public void setEmployeeCode(String employeeCode) {
		this.employeeCode = employeeCode;
	}



	public String getProjectAssignmentCode() {
		return projectAssignmentCode;
	}



	public void setProjectAssignmentCode(String projectAssignmentCode) {
		this.projectAssignmentCode = projectAssignmentCode;
	}



	public ProjectPerdiem getProjectPerdiem() {
		return projectPerdiem;
	}



	public void setProjectPerdiem(ProjectPerdiem projectPerdiem) {
		this.projectPerdiem = projectPerdiem;
	}



	public ProjectPerdiemDetail getProjectPerdiemDetail() {
		return projectPerdiemDetail;
	}



	public void setProjectPerdiemDetail(ProjectPerdiemDetail projectPerdiemDetail) {
		this.projectPerdiemDetail = projectPerdiemDetail;
	}



	public ProjectAssignment getProjectAssignment() {
		return projectAssignment;
	}



	public void setProjectAssignment(ProjectAssignment projectAssignment) {
		this.projectAssignment = projectAssignment;
	}



	public ProjectAssignmentDetail getProjectAssignmentDetail() {
		return projectAssignmentDetail;
	}



	public void setProjectAssignmentDetail(ProjectAssignmentDetail projectAssignmentDetail) {
		this.projectAssignmentDetail = projectAssignmentDetail;
	}
	public EmailUtil getEmailUtil() {
		return emailUtil;
	}
	public void setEmailUtil(EmailUtil emailUtil) {
		this.emailUtil = emailUtil;
	}
	public String getEMAIL_MESSAGE() {
		return EMAIL_MESSAGE;
	}
	public void setEMAIL_MESSAGE(String eMAIL_MESSAGE) {
		EMAIL_MESSAGE = eMAIL_MESSAGE;
	}
	public boolean isFORM_VALID() {
		return FORM_VALID;
	}
	public void setFORM_VALID(boolean fORM_VALID) {
		FORM_VALID = fORM_VALID;
	}
	public boolean isRenderDailog() {
		return renderDailog;
	}
	public void setRenderDailog(boolean renderDailog) {
		this.renderDailog = renderDailog;
	}
	public String getRevision() {
		return revision;
	}
	public void setRevision(String revision) {
		this.revision = revision;
	}
	public String getRevisionCount() {
		return revisionCount;
	}
	public void setRevisionCount(String revisionCount) {
		this.revisionCount = revisionCount;
	}
	public String getRevisionParameter() {
		return revisionParameter;
	}
	public void setRevisionParameter(String revisionParameter) {
		this.revisionParameter = revisionParameter;
	}
	public boolean isRecommendeRenderer() {
		return recommendeRenderer;
	}
	public void setRecommendeRenderer(boolean recommendeRenderer) {
		this.recommendeRenderer = recommendeRenderer;
	}
	public boolean isRecommendeDialogRenderer() {
		return recommendeDialogRenderer;
	}
	public void setRecommendeDialogRenderer(boolean recommendeDialogRenderer) {
		this.recommendeDialogRenderer = recommendeDialogRenderer;
	}
	public boolean isCheckForUpdatesRenderer() {
		return checkForUpdatesRenderer;
	}
	public void setCheckForUpdatesRenderer(boolean checkForUpdatesRenderer) {
		this.checkForUpdatesRenderer = checkForUpdatesRenderer;
	}
	public List<ProjectPerdiemDetail> getProjectPerdiemDetailsList() {
		return projectPerdiemDetailsList;
	}
	public void setProjectPerdiemDetailsList(
			List<ProjectPerdiemDetail> projectPerdiemDetailsList) {
		this.projectPerdiemDetailsList = projectPerdiemDetailsList;
	}

}
